package beautiful.butterfly.drds.binlog.command;


import beautiful.butterfly.drds.binlog.type.CommandType;
import beautiful.butterfly.drds.binlog.utils.ByteUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RequestBinaryLogCommand
{

    private long serverId;
    private String binlogFileName;
    private long binlogFilePosition;

    public RequestBinaryLogCommand(long serverId, String binlogFileName, long binlogFilePosition)
    {
        this.serverId = serverId;
        this.binlogFileName = binlogFileName;
        this.binlogFilePosition = binlogFilePosition;
    }

    public void write(ChannelHandlerContext channelHandlerContext)
    {
        log.info("get ready to send binary log request - serverid: " + this.serverId + " binlogName: "
                + this.binlogFileName + " position:" + this.binlogFilePosition);
        // LoggerUtils.debug(logger, "write RequestBinaryLogCommand");
        byte[] dumpBytes = ByteUtils.writeByte((byte) CommandType.binlog_dump.ordinal(), 1);
        byte[] binlogFilePositionBytes = ByteUtils.writeLong(this.binlogFilePosition, 4);
        byte[] flagBytes = ByteUtils.writeInt(0, 2); // flag
        byte[] serverIdBytes = ByteUtils.writeLong(this.serverId, 4);
        byte[] binlogFileNameBytes = this.binlogFileName.getBytes();

        // 然后开始构造头
        int totalCount = dumpBytes.length + binlogFilePositionBytes.length + flagBytes.length + serverIdBytes.length
                + binlogFileNameBytes.length;
        byte[] totalCountBytes = ByteUtils.writeInt(totalCount, 3);
        byte[] commandTypeBytes = new byte[1];
        commandTypeBytes[0] = 0;// 对于验证命令，这里就是1,其它都是0

        // 构造缓冲区并发送
        ByteBuf byteBuf = Unpooled.buffer(totalCount + 4);
        byteBuf.writeBytes(totalCountBytes).writeBytes(commandTypeBytes).writeBytes(dumpBytes)
                .writeBytes(binlogFilePositionBytes).writeBytes(flagBytes);
        byteBuf.writeBytes(serverIdBytes).writeBytes(binlogFileNameBytes);
        channelHandlerContext.channel().writeAndFlush(byteBuf);// 缓存清理
        // LoggerUtils.debug(logger, "准备发送请求二进制日志成功");
    }
}
